// 全局变量
let currentDocument = null;
let currentShareId = null;
let tocItems = [];

// DOM元素
const documentInfo = document.getElementById('documentInfo');
const documentContent = document.getElementById('documentContent');
const documentActions = document.getElementById('documentActions');
const loadingSpinner = document.getElementById('loadingSpinner');
const tocSidebar = document.getElementById('tocSidebar');
const tocNav = document.getElementById('tocNav');
const progressFill = document.getElementById('progressFill');
const shareModal = document.getElementById('shareModal');
const shareUrlInput = document.getElementById('shareUrlInput');
const shareStats = document.getElementById('shareStats');
const notification = document.getElementById('notification');

// 按钮元素
const toggleThemeBtn = document.getElementById('toggleTheme');
const toggleTocBtn = document.getElementById('toggleToc');
const exportHtmlBtn = document.getElementById('exportHtml');
const shareBtnHeader = document.getElementById('shareBtn');
const closeTocBtn = document.getElementById('closeToc');
const exportHtmlCard = document.getElementById('exportHtmlCard');
const printDocBtn = document.getElementById('printDoc');
const copyLinkBtn = document.getElementById('copyLink');
const closeShareModal = document.getElementById('closeShareModal');
const copyShareUrlBtn = document.getElementById('copyShareUrl');

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    initializeReader();
    setupEventListeners();
    loadDocument();
});

// 初始化阅读器
function initializeReader() {
    // 获取分享ID
    const pathParts = window.location.pathname.split('/');
    currentShareId = pathParts[pathParts.length - 1];
    
    // 设置分享链接
    shareUrlInput.value = window.location.href;
    
    // 初始化主题
    const savedTheme = localStorage.getItem('reader-theme') || 'light';
    setTheme(savedTheme);
    
    // 初始化目录状态
    initializeTocState();
    
    // 初始化阅读进度
    updateReadingProgress();
}

// 设置事件监听器
function setupEventListeners() {
    // 主题切换
    toggleThemeBtn.addEventListener('click', toggleTheme);
    
    // 目录切换
    toggleTocBtn.addEventListener('click', toggleToc);
    closeTocBtn.addEventListener('click', closeToc);
    
    // 导出功能
    exportHtmlBtn.addEventListener('click', exportToHtml);
    exportHtmlCard.addEventListener('click', exportToHtml);
    
    // 分享功能
    shareBtnHeader.addEventListener('click', openShareModal);
    copyLinkBtn.addEventListener('click', openShareModal);
    closeShareModal.addEventListener('click', closeShareModalFunc);
    copyShareUrlBtn.addEventListener('click', copyShareUrl);
    
    // 打印功能
    printDocBtn.addEventListener('click', printDocument);
    
    // 滚动事件
    window.addEventListener('scroll', updateReadingProgress);
    window.addEventListener('scroll', updateActiveHeading);
    
    // 模态框外部点击关闭
    shareModal.addEventListener('click', (e) => {
        if (e.target === shareModal) {
            closeShareModalFunc();
        }
    });
    
    // 键盘快捷键
    document.addEventListener('keydown', handleKeyboardShortcuts);
    
    // 窗口大小变化监听
    window.addEventListener('resize', handleWindowResize);
}

// 加载文档
async function loadDocument() {
    try {
        const response = await fetch(`/api/document/${currentShareId}`);
        
        if (!response.ok) {
            throw new Error('文档不存在或已被删除');
        }
        
        const document = await response.json();
        currentDocument = document;
        
        // 隐藏加载动画
        loadingSpinner.style.display = 'none';
        
        // 显示文档信息
        displayDocumentInfo(document);
        
        // 显示文档内容
        displayDocumentContent(document.htmlContent);
        
        // 生成目录
        generateToc();
        
        // 显示操作按钮
        documentActions.style.display = 'block';
        
        // 代码高亮
        if (typeof hljs !== 'undefined') {
            hljs.highlightAll();
        }
        
    } catch (error) {
        console.error('加载文档失败:', error);
        showError(error.message);
    }
}

// 显示文档信息
function displayDocumentInfo(document) {
    const uploadTime = new Date(document.uploadTime).toLocaleString('zh-CN');
    
    documentInfo.innerHTML = `
        <div class="doc-title">${document.title}</div>
        <div class="doc-meta">上传时间: ${uploadTime}</div>
    `;
    
    // 设置页面标题
    document.title = `${document.title} - 无界Markdown阅读器`;
}

// 显示文档内容
function displayDocumentContent(htmlContent) {
    documentContent.innerHTML = htmlContent;
    
    // 为所有标题添加ID
    const headings = documentContent.querySelectorAll('h1, h2, h3, h4, h5, h6');
    headings.forEach((heading, index) => {
        if (!heading.id) {
            heading.id = `heading-${index}`;
        }
    });
}

// 生成目录
function generateToc() {
    const headings = documentContent.querySelectorAll('h1, h2, h3, h4, h5, h6');
    tocItems = [];
    
    if (headings.length === 0) {
        tocNav.innerHTML = '<p style="color: #666; text-align: center;">此文档没有标题</p>';
        return;
    }
    
    const tocList = document.createElement('ul');
    
    headings.forEach((heading, index) => {
        const level = parseInt(heading.tagName.charAt(1));
        const text = heading.textContent.trim();
        const id = heading.id || `heading-${index}`;
        
        if (!heading.id) {
            heading.id = id;
        }
        
        const tocItem = {
            id: id,
            text: text,
            level: level,
            element: heading
        };
        
        tocItems.push(tocItem);
        
        const listItem = document.createElement('li');
        const link = document.createElement('a');
        link.href = `#${id}`;
        link.textContent = text;
        link.className = `toc-h${level}`;
        link.addEventListener('click', (e) => {
            e.preventDefault();
            scrollToHeading(id);
            if (window.innerWidth <= 768) {
                closeToc();
            }
        });
        
        listItem.appendChild(link);
        tocList.appendChild(listItem);
    });
    
    tocNav.innerHTML = '';
    tocNav.appendChild(tocList);
}

// 滚动到指定标题
function scrollToHeading(headingId) {
    const heading = document.getElementById(headingId);
    if (heading) {
        const headerHeight = document.querySelector('.reader-header').offsetHeight;
        const targetPosition = heading.offsetTop - headerHeight - 20;
        
        window.scrollTo({
            top: targetPosition,
            behavior: 'smooth'
        });
    }
}

// 更新活跃标题
function updateActiveHeading() {
    if (tocItems.length === 0) return;
    
    const headerHeight = document.querySelector('.reader-header').offsetHeight;
    const scrollPosition = window.scrollY + headerHeight + 50;
    
    let activeHeading = null;
    
    for (let i = tocItems.length - 1; i >= 0; i--) {
        const heading = tocItems[i].element;
        if (heading.offsetTop <= scrollPosition) {
            activeHeading = tocItems[i];
            break;
        }
    }
    
    // 更新目录中的活跃状态
    const tocLinks = tocNav.querySelectorAll('a');
    tocLinks.forEach(link => link.classList.remove('active'));
    
    if (activeHeading) {
        const activeLink = tocNav.querySelector(`a[href="#${activeHeading.id}"]`);
        if (activeLink) {
            activeLink.classList.add('active');
        }
    }
}

// 更新阅读进度
function updateReadingProgress() {
    const documentHeight = document.documentElement.scrollHeight - window.innerHeight;
    const scrolled = window.scrollY;
    const progress = documentHeight > 0 ? (scrolled / documentHeight) * 100 : 0;
    
    progressFill.style.width = `${Math.min(progress, 100)}%`;
}

// 主题切换
function toggleTheme() {
    const currentTheme = document.documentElement.getAttribute('data-theme') || 'light';
    const newTheme = currentTheme === 'light' ? 'dark' : 'light';
    setTheme(newTheme);
}

function setTheme(theme) {
    document.documentElement.setAttribute('data-theme', theme);
    localStorage.setItem('reader-theme', theme);
    
    // 更新主题按钮图标
    toggleThemeBtn.textContent = theme === 'light' ? '🌙' : '☀️';
}

// 目录切换
function toggleToc() {
    // 在移动端才使用show类来控制显示/隐藏
    if (window.innerWidth <= 768) {
        tocSidebar.classList.toggle('show');
    } else {
        // 在桌面端切换整个侧边栏的可见性
        if (tocSidebar.style.display === 'none') {
            tocSidebar.style.display = 'block';
        } else {
            tocSidebar.style.display = 'none';
        }
    }
}

function closeToc() {
    if (window.innerWidth <= 768) {
        tocSidebar.classList.remove('show');
    } else {
        tocSidebar.style.display = 'none';
    }
}

// 初始化目录状态
function initializeTocState() {
    if (window.innerWidth <= 768) {
        // 移动端默认隐藏
        tocSidebar.classList.remove('show');
    } else {
        // 桌面端默认显示
        tocSidebar.style.display = 'block';
    }
}

// 处理窗口大小变化
function handleWindowResize() {
    // 重新初始化目录状态
    initializeTocState();
}

// 导出为HTML
function exportToHtml() {
    if (!currentShareId) {
        showNotification('无法导出文档', 'error');
        return;
    }
    
    const exportUrl = `/api/export/html/${currentShareId}`;
    window.open(exportUrl, '_blank');
    showNotification('正在下载HTML文件...', 'info');
}

// 打印文档
function printDocument() {
    window.print();
}

// 分享功能
function openShareModal() {
    shareModal.classList.add('show');
    
    // 更新统计信息
    updateShareStats();
}

function closeShareModalFunc() {
    shareModal.classList.remove('show');
}

function copyShareUrl() {
    shareUrlInput.select();
    shareUrlInput.setSelectionRange(0, 99999);
    
    try {
        document.execCommand('copy');
        showNotification('链接已复制到剪贴板', 'success');
        
        // 临时改变按钮文本
        const originalText = copyShareUrlBtn.textContent;
        copyShareUrlBtn.textContent = '已复制！';
        setTimeout(() => {
            copyShareUrlBtn.textContent = originalText;
        }, 2000);
    } catch (err) {
        if (navigator.clipboard) {
            navigator.clipboard.writeText(shareUrlInput.value).then(() => {
                showNotification('链接已复制到剪贴板', 'success');
            }).catch(() => {
                showNotification('复制失败，请手动复制', 'error');
            });
        } else {
            showNotification('复制失败，请手动复制', 'error');
        }
    }
}

// 更新分享统计
async function updateShareStats() {
    try {
        const response = await fetch(`/api/documents`);
        if (response.ok) {
            const documents = await response.json();
            const currentDoc = documents.find(doc => doc.id === currentShareId);
            
            if (currentDoc) {
                const lastViewed = currentDoc.lastViewed 
                    ? new Date(currentDoc.lastViewed).toLocaleString('zh-CN')
                    : '暂无';
                
                shareStats.innerHTML = `
                    <div style="display: flex; justify-content: space-between; margin-bottom: 10px;">
                        <span>📊 访问次数:</span>
                        <strong>${currentDoc.views || 0}</strong>
                    </div>
                    <div style="display: flex; justify-content: space-between;">
                        <span>🕒 最后访问:</span>
                        <span>${lastViewed}</span>
                    </div>
                `;
            }
        }
    } catch (error) {
        console.error('获取统计信息失败:', error);
    }
}

// 键盘快捷键
function handleKeyboardShortcuts(e) {
    // Ctrl/Cmd + K: 切换目录
    if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
        e.preventDefault();
        toggleToc();
    }
    
    // Ctrl/Cmd + Shift + D: 切换主题
    if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === 'D') {
        e.preventDefault();
        toggleTheme();
    }
    
    // Ctrl/Cmd + P: 打印
    if ((e.ctrlKey || e.metaKey) && e.key === 'p') {
        // 让浏览器处理默认的打印功能
        return;
    }
    
    // Escape: 关闭模态框和侧边栏
    if (e.key === 'Escape') {
        closeShareModalFunc();
        closeToc();
    }
}

// 显示通知
function showNotification(message, type = 'info') {
    notification.textContent = message;
    notification.className = `notification ${type}`;
    notification.classList.add('show');
    
    setTimeout(() => {
        notification.classList.remove('show');
    }, 3000);
}

// 显示错误
function showError(message) {
    loadingSpinner.style.display = 'none';
    
    documentInfo.innerHTML = `
        <div style="text-align: center; padding: 60px 20px;">
            <div style="font-size: 4rem; margin-bottom: 20px;">😞</div>
            <h2 style="color: #dc3545; margin-bottom: 15px;">加载失败</h2>
            <p style="color: #666; margin-bottom: 30px;">${message}</p>
            <a href="/" style="
                display: inline-block;
                background: var(--primary-color);
                color: white;
                padding: 12px 24px;
                border-radius: 8px;
                text-decoration: none;
                font-weight: 600;
            ">返回首页</a>
        </div>
    `;
}

// 工具函数：防抖
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 优化滚动事件性能
const debouncedUpdateProgress = debounce(updateReadingProgress, 10);
const debouncedUpdateHeading = debounce(updateActiveHeading, 100);

window.removeEventListener('scroll', updateReadingProgress);
window.removeEventListener('scroll', updateActiveHeading);
window.addEventListener('scroll', debouncedUpdateProgress);
window.addEventListener('scroll', debouncedUpdateHeading);

// 错误处理
window.addEventListener('error', (event) => {
    console.error('页面错误:', event.error);
});

window.addEventListener('unhandledrejection', (event) => {
    console.error('未处理的Promise拒绝:', event.reason);
    event.preventDefault();
});